import urllib.request
import json
from urllib import parse

# # 1.第一版基础的请求
# # 获取请求url
# url = 'https://httpbin.org/get'
# # 发起请求
# response = urllib.request.urlopen(url)
# # 得到字节流
# response_byte = response.read()
# # 将字节流转换为字符串
# response_str = response_byte.decode('utf-8')
# # 将字符串转换为字典
# response_json = json.loads(response_str)
# print(response_json['headers']['User-Agent'],response_json['args'])


#
# #2. 传递请求参数
# data={"age":18,"name":"zzf"}
# # 将字典转为Unicode字符串
# data_str = parse.urlencode(data)
# # 将把 Unicode 字符串 → 字节串
# data_bytes=data_str.encode()
#
# # 获取请求url
# url = f'https://httpbin.org/get?{data_bytes}'
# # 构造请求实例
# req = urllib.request.Request(url)
# # 发起请求
# response = urllib.request.urlopen(req)
# # 得到字节流
# response_bytes = response.read()
# # 把字节串（bytes） → 人类可读的 Unicode 字符串（str）
# response_str = response_bytes.decode('utf-8')
# # 将字符串转换为字典
# response_json = json.loads(response_str)
# print(response_json['headers']['User-Agent'],response_json['args'])


#
# # 3.发送表单（x-www-form-urlencoded）的 POST  data_bytes的数据在 form中
# # 传递请求参数
# data={"age":18,"name":"zzf"}
# # 将字典转为Unicode字符串
# data_str = parse.urlencode(data)
# # 将把 Unicode 字符串 → 字节串
# data_bytes=data_str.encode()
#
# # 获取请求url
# url = f'https://httpbin.org/post?sex=n'
# # 构造请求实例
# req = urllib.request.Request(url
#                              ,data=data_bytes,
#                              headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
#                                       'Content-Type': 'application/x-www-form-urlencoded'}
#                              )
# # 发起请求
# response = urllib.request.urlopen(req)
# # 得到字节流
# response_bytes = response.read()
# # 把字节串（bytes） → 人类可读的 Unicode 字符串（str）
# response_str = response_bytes.decode('utf-8')
# # 将字符串转换为字典
# response_json = json.loads(response_str)
# print(response_json['headers']['User-Agent'],response_json['args'])
# print(response_json)
#
#
#
#
#
# # 4.发送 JSON 的 POST  data_bytes的数据在 data中
# # 传递请求参数
# data={"age":18,"name":"zzf"}
# # 将字典转为Unicode字符串
# data_str = json.dumps(data)
# # 将把 Unicode 字符串 → 字节串
# data_bytes=data_str.encode()
#
# # 获取请求url
# url = f'https://httpbin.org/post?sex=n'
# # 构造请求实例
# req = urllib.request.Request(url
#                              ,data=data_bytes,
#                              headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
#                                       'Content-Type': 'json'}
#                              )
# # 发起请求
# response = urllib.request.urlopen(req)
# # 得到字节流
# response_bytes = response.read()
# # 把字节串（bytes） → 人类可读的 Unicode 字符串（str）
# response_str = response_bytes.decode('utf-8')
# # 将字符串转换为字典
# response_json = json.loads(response_str)
# print(response_json['headers']['User-Agent'],response_json['args'])
# print(response_json)


